package com.huhu.sys.filter;

import com.huhu.service.UserService;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**RememberMe的功能，参考博客：http://www.tuicool.com/articles/NfAFBz
 * Created by xuyi on 2016/10/1.
 */
public class RememberAuthFilter extends FormAuthenticationFilter {

    @Autowired
    private UserService userService;

    public RememberAuthFilter() {
        super();
    }
    //这个方法决定了是否让用户登录
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        Subject subject = getSubject(request, response);
        //如果subject.isAuthenticated()为 false 证明不是登录的，同时subject.isRemembered() 为 true
        //证明是通过RememberMe来登录的
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            //获取Session 看看是不是空的
            Session session = subject.getSession(true);
            if (session.getAttribute("userId") == null) {
                //为空，初始化
                String userName = subject.getPrincipal().toString();

                userService.initUser(userName);
            }
        }
        //这个方法本来只返回 subject.isAuthenticated() 现在我们加上 subject.isRemembered() 让它同时也兼容remember这种情况
        return subject.isAuthenticated() || subject.isRemembered();
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response)
            throws Exception {




        return false;
    }
}
